import axios from 'axios';

export const services = axios.create({
  baseURL: 'http://192.168.10.5:8081',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'Cache-Control': 'no-cache, no-store, must-revalidate',
    'Pragma': 'no-cache',
    'Expires': '0'
  }
});

// 请求拦截器
services.interceptors.request.use(config => {
  const userId = localStorage.getItem('userId');
  const accessToken = localStorage.getItem('accessToken');
  
  // 确保X-User-Id存在
  if (userId) {
    config.headers['X-User-Id'] = userId;
  }
  
  // 添加Authorization头
  if (accessToken) {
    config.headers['Authorization'] = `Bearer ${accessToken}`;
  }
  
  // 移动端特殊处理
  if (isMobile()) {
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    config.headers['Accept'] = 'application/json';
  }
  
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器
services.interceptors.response.use(response => {
  return response;
}, error => {
  // 移动端特殊错误处理
  if (isMobile() && error.response && error.response.status === 401) {
    localStorage.removeItem('accessToken');
    window.location.href = '/login';
  }
  return Promise.reject(error);
});

// 检测移动端
function isMobile() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

export default services;